package com.dao;

import com.model.Blog;
import com.model.User;
import com.utils.DbUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/11.
 */
public class UserDao {

    private Connection connection;

    public UserDao() {
        //在这里初始化
        connection = DbUtil.getConnection();
    }

    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        try {
            Statement statement = connection.createStatement();
            //这里是查询select * from blogs
            ResultSet rs = statement.executeQuery("select * from users ");
            while (rs.next()) {
                User user = new User();
                user.setUserName(rs.getString("user_name"));
                user.setPassword(rs.getString("password"));

                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }

    public List<User> JudgeUsers(String name , String pwd) {
        List<User> users = new ArrayList<User>();
        try {
            Statement statement = connection.createStatement();
            //这里是查询select * from blogs
            String sql = " select * from users where user_name = '"+name+"' and  password = '"+pwd+"' ";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                User user = new User();
                user.setUserName(rs.getString("user_name"));
                user.setPassword(rs.getString("password"));

                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }

    public int writeUsers(String number,String name , String pwd){

        int boo = 0;
        int userNumber = 0;
        try {
            Statement statement = connection.createStatement();

            String sql1="select count(id) from users";
            ResultSet rs = statement.executeQuery(sql1);
            while (rs.next()) {
                userNumber = rs.getInt("count(id)");
                userNumber++;
            }

            String sql2=" INSERT INTO blog.`users` (`id`, `user_name`, `password`, `PhoneNumber`) VALUES ('"+userNumber+"', '"+name+"', '"+pwd+"', '"+number+"') ";

            //这里是查询select * from blogs
            boo = statement.executeUpdate(sql2);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        return boo;
    }
}
